/**
 * 短信通知服务
 * 支持从系统配置表读取模板和配置，集成第三方短信服务商
 */

const { query } = require('../config/db');
const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
const OpenApi = require('@alicloud/openapi-client');
const Util = require('@alicloud/tea-util');
const Credential = require('@alicloud/credentials');

/**
 * 从系统配置表获取配置
 * @param {string} configKey - 配置键
 * @returns {Promise<string>} 配置值
 */
async function getConfig(configKey) {
  try {
    const result = await query(
      'SELECT config_value FROM system_configs WHERE config_key = ?',
      [configKey]
    );
    
    if (result && result.length > 0) {
      return result[0].config_value;
    }
    
    return null;
  } catch (error) {
    console.error(`获取配置 ${configKey} 失败:`, error);
    return null;
  }
}

/**
 * 渲染短信模板
 * @param {string} template - 模板内容
 * @param {Object} variables - 变量数据
 * @returns {string} 渲染后的内容
 */
function renderTemplate(template, variables) {
  if (!template || !variables) {
    return template || '';
  }

  let renderedContent = template;
  
  // 替换模板中的变量占位符
  Object.keys(variables).forEach(key => {
    const placeholder = `{${key}}`;
    const value = variables[key] || '';
    renderedContent = renderedContent.replace(new RegExp(placeholder, 'g'), value);
  });

  return renderedContent;
}

/**
 * 验证手机号格式
 * @param {string} phoneNumber - 手机号码
 * @returns {boolean} 是否有效
 */
function validatePhoneNumber(phoneNumber) {
  if (!phoneNumber) return false;
  
  // 简单的手机号验证（11位数字，以1开头）
  const phoneRegex = /^1[3-9]\d{9}$/;
  return phoneRegex.test(phoneNumber);
}

/**
 * 发送订单通知短信
 * @param {string} phoneNumber - 手机号码
 * @param {Object} orderDetails - 订单详情
 * @param {string} orderDetails.order_number - 订单号
 * @param {string} orderDetails.license_plate - 车牌号
 * @param {string} orderDetails.parking_lot_name - 停车场名称
 * @param {string} orderDetails.planned_start_time - 计划开始时间
 * @param {string} orderDetails.planned_end_time - 计划结束时间
 * @param {number} orderDetails.final_amount - 最终金额
 * @returns {Promise<Object>} 发送结果
 */
async function sendOrderNotification(phoneNumber, orderDetails) {
  try {
    // 参数验证
    if (!phoneNumber || !orderDetails) {
      console.log('短信发送跳过: 手机号码或订单详情为空');
      return {
        success: false,
        message: '手机号码和订单详情不能为空',
        skip: true
      };
    }

    if (!orderDetails.order_number) {
      console.log('短信发送跳过: 订单号为空');
      return {
        success: false,
        message: '订单号不能为空',
        skip: true
      };
    }

    // 验证手机号格式
    if (!validatePhoneNumber(phoneNumber)) {
      console.log(`短信发送跳过: 手机号格式无效 ${phoneNumber}`);
      return {
        success: false,
        message: '手机号格式无效',
        skip: true
      };
    }

    // 检查短信功能是否启用
    const smsEnabled = await getConfig('sms_enabled');
    if (smsEnabled !== 'true') {
      console.log('短信发送跳过: 短信功能未启用');
      return {
        success: false,
        message: '短信功能未启用',
        skip: true
      };
    }

    // 获取短信模板
    const template = await getConfig('sms_order_template');
    if (!template) {
      console.log('短信发送跳过: 未找到订单短信模板');
      return {
        success: false,
        message: '未找到订单短信模板',
        skip: true
      };
    }

    // 格式化时间
    const formatTime = (timeString) => {
      if (!timeString) return '';
      try {
        const date = new Date(timeString);
        return date.toLocaleString('zh-CN', {
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        });
      } catch (error) {
        return timeString;
      }
    };

    // 准备模板变量
    const variables = {
      order_number: orderDetails.order_number,
      订单号: orderDetails.order_number,
      license_plate: orderDetails.license_plate || '',
      车牌号: orderDetails.license_plate || '',
      parking_lot_name: orderDetails.parking_lot_name || '',
      停车场名称: orderDetails.parking_lot_name || '',
      start_time: formatTime(orderDetails.planned_start_time),
      开始时间: formatTime(orderDetails.planned_start_time),
      end_time: formatTime(orderDetails.planned_end_time),
      结束时间: formatTime(orderDetails.planned_end_time),
      amount: orderDetails.final_amount || 0,
      费用: orderDetails.final_amount || 0
    };

    // 渲染短信内容
    const smsContent = renderTemplate(template, variables);
    
    // 获取服务商配置
    const providerConfig = await getConfig('sms_provider_config');
    const providerType = await getConfig('sms_provider_type');

    // 获取服务商配置并发送短信
    if (!providerConfig) {
      console.log('短信发送跳过: 未找到服务商配置');
      return {
        success: false,
        message: '未找到服务商配置',
        skip: true
      };
    }

    let config;
    try {
      config = JSON.parse(providerConfig);
    } catch (error) {
      console.log('短信发送跳过: 服务商配置格式错误');
      return {
        success: false,
        message: '服务商配置格式错误',
        skip: true
      };
    }

    // 根据服务商类型发送短信
    if (providerType === 'aliyun') {
      // 使用阿里云发送短信
      if (!config.accessKeyId || !config.accessKeySecret || !config.signName) {
        console.log('短信发送失败: 阿里云配置不完整');
        return {
          success: false,
          message: '阿里云短信配置不完整，请检查AccessKeyId、AccessKeySecret和签名配置',
          skip: true
        };
      }

      // 获取阿里云模板代码
      const templateCode = await getConfig('sms_aliyun_template_code');
      if (!templateCode) {
        console.log('短信发送跳过: 未找到阿里云模板代码');
        return {
          success: false,
          message: '未找到阿里云模板代码',
          skip: true
        };
      }

      // 构建阿里云模板参数
      const templateParam = {
        order_number: orderDetails.order_number,
        license_plate: orderDetails.license_plate || '',
        parking_lot_name: orderDetails.parking_lot_name || '',
        start_time: formatTime(orderDetails.planned_start_time),
        end_time: formatTime(orderDetails.planned_end_time),
        amount: orderDetails.final_amount || 0
      };

      return await sendAliyunSms(
        phoneNumber,
        config.signName,
        templateCode,
        templateParam,
        config
      );

    } else {
      // 其他服务商或模拟发送
      console.log('=== 短信通知发送（模拟）===');
      console.log(`收件人: ${phoneNumber}`);
      console.log(`内容: ${smsContent}`);
      console.log(`服务商: ${providerType || '未配置'}`);
      console.log(`发送时间: ${new Date().toLocaleString('zh-CN')}`);
      console.log('============================');

      // 模拟发送延迟
      await new Promise(resolve => setTimeout(resolve, 100));

      return {
        success: true,
        message: '短信发送成功（模拟）',
        data: {
          phone: phoneNumber,
          content: smsContent,
          send_time: new Date().toISOString(),
          message_id: `mock_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
        }
      };
    }

  } catch (error) {
    console.error('短信发送失败:', error);
    return {
      success: false,
      message: error.message || '短信发送失败',
      error: error
    };
  }
}

/**
 * 测试短信配置
 * @param {string} testPhone - 测试手机号
 * @returns {Promise<Object>} 测试结果
 */
async function testSmsConfig(testPhone) {
  try {
    if (!validatePhoneNumber(testPhone)) {
      return {
        success: false,
        message: '测试手机号格式无效'
      };
    }

    // 检查短信功能是否启用
    const smsEnabled = await getConfig('sms_enabled');
    if (smsEnabled !== 'true') {
      return {
        success: false,
        message: '短信功能未启用'
      };
    }

    // 获取配置
    const template = await getConfig('sms_order_template');
    const providerConfig = await getConfig('sms_provider_config');
    const providerType = await getConfig('sms_provider_type');

    if (!template) {
      return {
        success: false,
        message: '未找到短信模板配置'
      };
    }

    if (!providerConfig || !providerType) {
      return {
        success: false,
        message: '未找到短信服务商配置'
      };
    }

    // 构建测试数据（使用符合阿里云规范的车牌号格式）
    const testOrderDetails = {
      order_number: 'TEST' + Date.now(),
      license_plate: '京A12345',
      parking_lot_name: 'TestParking',
      planned_start_time: new Date().toISOString(),
      planned_end_time: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
      final_amount: 10.00
    };

    // 发送测试短信
    const result = await sendOrderNotification(testPhone, testOrderDetails);
    
    return {
      success: result.success,
      message: result.success ? '测试短信发送成功' : result.message,
      data: result.data
    };

  } catch (error) {
    console.error('测试短信配置失败:', error);
    return {
      success: false,
      message: error.message || '测试短信配置失败'
    };
  }
}

/**
 * 发送优惠券到账通知
 * @param {string} phoneNumber - 手机号码
 * @param {Object} couponDetails - 优惠券详情
 * @returns {Promise<Object>} 发送结果
 */
async function sendCouponNotification(phoneNumber, couponDetails) {
  try {
    const { template_name, expiry_date } = couponDetails;
    
    const expiryDateStr = new Date(expiry_date).toLocaleDateString('zh-CN');
    const content = `【省米停车】恭喜您获得优惠券"${template_name}"，有效期至${expiryDateStr}，快去使用吧！`;

    console.log('=== 优惠券通知模拟发送 ===');
    console.log(`收件人: ${phoneNumber}`);
    console.log(`内容: ${content}`);
    console.log(`发送时间: ${new Date().toLocaleString('zh-CN')}`);
    console.log('==========================');

    await new Promise(resolve => setTimeout(resolve, 100));

    return {
      success: true,
      message: '优惠券通知发送成功（模拟）',
      data: {
        phone: phoneNumber,
        content: content,
        send_time: new Date().toISOString(),
        message_id: `mock_coupon_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
      }
    };

  } catch (error) {
    console.error('优惠券通知发送失败:', error);
    return {
      success: false,
      message: error.message || '优惠券通知发送失败',
      error: error
    };
  }
}

/**
 * 发送系统通知短信
 * @param {string} phoneNumber - 手机号码
 * @param {string} message - 通知内容
 * @returns {Promise<Object>} 发送结果
 */
async function sendSystemNotification(phoneNumber, message) {
  try {
    const content = `【省米停车】${message}`;

    console.log('=== 系统通知模拟发送 ===');
    console.log(`收件人: ${phoneNumber}`);
    console.log(`内容: ${content}`);
    console.log(`发送时间: ${new Date().toLocaleString('zh-CN')}`);
    console.log('========================');

    await new Promise(resolve => setTimeout(resolve, 100));

    return {
      success: true,
      message: '系统通知发送成功（模拟）',
      data: {
        phone: phoneNumber,
        content: content,
        send_time: new Date().toISOString(),
        message_id: `mock_system_${Date.now()}_${Math.random().toString(36).substring(2, 11)}`
      }
    };

  } catch (error) {
    console.error('系统通知发送失败:', error);
    return {
      success: false,
      message: error.message || '系统通知发送失败',
      error: error
    };
  }
}

/**
 * 创建阿里云短信客户端
 * @param {Object} config - 阿里云配置
 * @returns {Object} 阿里云短信客户端
 */
function createAliyunSmsClient(config) {
  try {
    // 使用AccessKey配置凭据
    const credentialsConfig = new Credential.Config({
      type: 'access_key',
      accessKeyId: config.accessKeyId,
      accessKeySecret: config.accessKeySecret
    });

    const credential = new Credential.default(credentialsConfig);

    const openApiConfig = new OpenApi.Config({
      credential: credential,
      endpoint: 'dysmsapi.aliyuncs.com'
    });

    return new Dysmsapi20170525.default(openApiConfig);
  } catch (error) {
    console.error('创建阿里云短信客户端失败:', error);
    throw error;
  }
}

/**
 * 通过阿里云发送短信
 * @param {string} phoneNumber - 手机号码
 * @param {string} signName - 短信签名
 * @param {string} templateCode - 模板代码
 * @param {Object} templateParam - 模板参数
 * @param {Object} config - 阿里云配置
 * @returns {Promise<Object>} 发送结果
 */
async function sendAliyunSms(phoneNumber, signName, templateCode, templateParam, config) {
  try {
    const client = createAliyunSmsClient(config);
    
    const sendSmsRequest = new Dysmsapi20170525.SendSmsRequest({
      phoneNumbers: phoneNumber,
      signName: signName,
      templateCode: templateCode,
      templateParam: JSON.stringify(templateParam)
    });

    const runtime = new Util.RuntimeOptions({});
    const response = await client.sendSmsWithOptions(sendSmsRequest, runtime);

    console.log('阿里云短信发送响应:', response);

    // 检查响应结果
    if (response && response.body && response.body.code === 'OK') {
      return {
        success: true,
        message: '短信发送成功',
        data: {
          messageId: response.body.bizId,
          requestId: response.body.requestId,
          code: response.body.code,
          message: response.body.message
        }
      };
    } else {
      return {
        success: false,
        message: response?.body?.message || '短信发送失败',
        data: response?.body
      };
    }

  } catch (error) {
    console.error('阿里云短信发送失败:', error);

    // 处理特定的阿里云错误
    let errorMessage = '短信发送异常';
    if (error.code === 'InvalidAccessKeyId.NotFound') {
      errorMessage = '阿里云AccessKey配置无效，请检查AccessKeyId是否正确';
    } else if (error.code === 'SignatureDoesNotMatch') {
      errorMessage = '阿里云AccessKeySecret配置无效，请检查AccessKeySecret是否正确';
    } else if (error.code === 'InvalidTemplateCode.MalFormed') {
      errorMessage = '阿里云短信模板代码无效，请检查模板代码是否正确';
    } else if (error.code === 'InvalidSignName.MalFormed') {
      errorMessage = '阿里云短信签名无效，请检查签名是否正确';
    } else if (error.message) {
      errorMessage = error.message;
    }

    return {
      success: false,
      message: errorMessage,
      error: error
    };
  }
}

module.exports = {
  sendOrderNotification,
  sendCouponNotification,
  sendSystemNotification,
  getConfig,
  renderTemplate,
  validatePhoneNumber,
  testSmsConfig,
  sendAliyunSms,
  createAliyunSmsClient
};
